//
//  ContactUtil.m
//  timelyRain
//
//  Created by Jiafei Wei on 16/9/19.
//  Copyright © 2016年 Jiafei Wei. All rights reserved.
//

#import "ContactUtil.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "TContact.h"
#import "DbManage.h"
#import "HttpTool.h"
#import "MJExtension.h"
#import "RunSucessInfo.h"
#import "NewContactDao.h"
#import "StringTool.h"
@implementation ContactUtil

static ContactUtil *instance;
//单例模式
+(ContactUtil *)share{
    @synchronized (self) {
        if(instance==nil) {
            instance = [[ContactUtil alloc]init];
            [instance setCallContacBack];
            [instance queryContact];
    }
}
    return instance;
}
-(void)setCallContacBack{
    ABAddressBookRef addresBook = ABAddressBookCreateWithOptions(NULL, NULL);
    ABAddressBookRegisterExternalChangeCallback(addresBook, ContactsChangeCallback, nil);
}
#pragma mark - 获取手机所有联系人
-(NSMutableArray *)obtainPhoneAllContact
{
    //这个变量用于记录授权是否成功，即用户是否允许我们访问通讯录
    NSMutableArray *contactsSource  =[NSMutableArray array];
    int   __block tip=0;
    //声明一个通讯簿的引用
    ABAddressBookRef addBook =nil;
    //因为在IOS6.0之后和之前的权限申请方式有所差别，这里做个判断
    if   ([[UIDevice currentDevice].systemVersion floatValue]>=6.0) {
        //创建通讯簿的引用
        addBook=ABAddressBookCreateWithOptions(NULL, NULL);
        //创建一个出事信号量为0的信号
        dispatch_semaphore_t sema=dispatch_semaphore_create(0);
        //申请访问权限
        ABAddressBookRequestAccessWithCompletion(addBook, ^( bool   greanted, CFErrorRef error)        {
            //greanted为YES是表示用户允许，否则为不允许
            if   (!greanted) {
                tip=1;
            }
            //发送一次信号
            dispatch_semaphore_signal(sema);
        });
        //等待信号触发
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    } else {
        //IOS6之前
        addBook =ABAddressBookCreate();
    }
    if   (tip) {
        //做一个友好的提示
        UIAlertView * alart = [[UIAlertView alloc]initWithTitle:@ "温馨提示"   message:@ "请您设置允许APP访问您的通讯录\nSettings>General>Privacy"   delegate:self cancelButtonTitle:@ "确定"   otherButtonTitles:nil, nil];
        [alart show];
        return contactsSource;
    }
    
    //获取所有联系人的数组
    CFArrayRef allLinkPeople = ABAddressBookCopyArrayOfAllPeople(addBook);
    //获取联系人总数
    CFIndex number = ABAddressBookGetPersonCount(addBook);
    //进行遍历
    for(NSInteger i=0; i<number; i++) {
        //获取联系人对象的引用
        TContact  *t =[[TContact alloc]init];
        ABRecordRef  people = CFArrayGetValueAtIndex(allLinkPeople, i);
        ABRecordID recordID =ABRecordGetRecordID(people);
        NSLog(@"recordID===%d",recordID);
        t.reallyId =[NSString stringWithFormat:@"%d",recordID];
        //获取当前联系人名字
        NSString*firstName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonFirstNameProperty));
        //获取当前联系人姓氏
        NSString*lastName=(__bridge NSString *)(ABRecordCopyValue(people, kABPersonLastNameProperty));
        
        //获取当前联系人的公司
        NSString*organization=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonOrganizationProperty));
        //获取当前联系人的职位
        NSString*job=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonJobTitleProperty));
        //获取当前联系人的部门
        NSString*department=(__bridge NSString*)(ABRecordCopyValue(people, kABPersonDepartmentProperty));
        //获取当前联系人的电话 数组
        NSMutableArray * phoneArr = [[NSMutableArray alloc]init];
        NSString *phoneString =@"";
        ABMultiValueRef phones= ABRecordCopyValue(people, kABPersonPhoneProperty);
        for(NSInteger j=0; j<ABMultiValueGetCount(phones);j++) {
            [phoneArr addObject:(__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j))];
            NSLog(@"phone=======%@",phoneArr);
            [phoneString stringByAppendingString:(__bridge NSString *)(ABMultiValueCopyValueAtIndex(phones, j))];
        }
        
        //获取当前联系人头像图片
        NSData*userImage=(__bridge NSData*)(ABPersonCopyImageData(people));
        
        if (lastName == NULL && firstName != NULL) {
            NSLog(@"姓名：%@",firstName);
            t.name =firstName;
        }
        else if (firstName == NULL  && lastName != NULL)
        {
            NSLog(@"姓名：%@",lastName);
            t.name =lastName;
        }
        else if(firstName != NULL && lastName != NULL){
            NSLog(@"姓名：%@%@",lastName,firstName);
            NSString *name =[NSString stringWithFormat:@"%@%@",lastName,firstName];
            t.name =name;
        }else{
            t.name=@"";
        }
        t.group=@"";
        if (phoneArr.count!=0) {
            for (int i=0; i<phoneArr.count; i++) {
                NSLog(@"phone===a=sas：%@",[phoneArr objectAtIndex:i]);
               t.phone=[StringTool stringDeleteString:[phoneArr objectAtIndex:i]];
            }
        }
        if (t.phone!=NULL) {
            [contactsSource addObject:t];
        }
        //根据名字去找
        if (userImage == NULL) {//把联系人读出来
            NSLog(@"头像为空");
        }
    }
    if(addBook)
        CFRelease(addBook);
    return  contactsSource;
}

/*
 回调函数，实现自己的逻辑。
 */
void ContactsChangeCallback (ABAddressBookRef addressBook,
                             CFDictionaryRef info,
                             void *context){
    NSLog(@"ContactsChangeCallback");
    [instance queryContact];//再次查询
}

-(void)queryContact{
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //查出来所有的数据
        DbManage *db =[DbManage shareDbManage];
        NSMutableArray *contactArr =[self obtainPhoneAllContact];
        [db deleteContactAll];
        [db insertConatctArray:contactArr];
        [instance writeJson:contactArr];
    });
}
-(void)writeJson:(NSArray *)contactArray{
    NSString *doc =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)lastObject];
    NSString *plistPath =[doc stringByAppendingPathComponent:@"contact.plist"];
    NSMutableArray *ar =[NSMutableArray array];
    if (contactArray.count!=0) {
        for (TContact *t in contactArray) {
                NSDictionary* dic = [instance conatctChanggeDic:t];
                [ar addObject:dic];
        }
    }
    //这里其实是返回的结果的
    [[ar mj_JSONString] writeToFile:plistPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
     NSLog(@"plistPath====%@",[ar mj_JSONString]);
    //发送读取成功的通知
    NSNotification * notice = [NSNotification notificationWithName:@"conatctState" object:nil userInfo:@{@"readContactSucess":@true}];
    [[NSNotificationCenter defaultCenter]postNotification:notice];
}
-(NSDictionary *)conatctChanggeDic:(TContact *)t{
    NSDictionary *dic =@{@"contactId":t.reallyId,@"displayName":t.name,
                         @"phoneNum":t.phone,@"sortKey":@"",
                         @"photoId":@0,@"lookUpKey":@"",
                         @"selected":@0,@"formattedNumber":@"",
                         @"pinyin":@"",@"version":@"",
                         @"note":@"",@"group_id":@0,
                         @"group_name":t.group};
//    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
//    [dic setObject:t.reallyId forKey:@"contactId"];
//    [dic setObject:t.name forKey:@"displayName"];
//    [dic setObject:t.phone forKey:@"phoneNum"];
//    [dic setObject:@"" forKey:@"sortKey"];
//    //[dic setObject:@0 forKey:@"photoId"];
//    [dic setObject:@"" forKey:@"lookUpKey"];
//    [dic setObject:@0 forKey:@"selected"];
//     [dic setObject:@"" forKey:@"formattedNumber"];
//    [dic setObject:@"" forKey:@"pinyin"];
//    [dic setObject:@"" forKey:@"version"];
//    [dic setObject:@"" forKey:@"note"];
//    [dic setObject:@0 forKey:@"group_id"];
//    [dic setObject:t.group forKey:@"group_name"];
    return dic;
}
-(NSMutableDictionary *)conatctChanggeString:(TContact *)t{
    NewContactDao *dao =[[NewContactDao alloc]init];
    dao.contactId =[t.reallyId intValue];
    dao.displayName =t.name;
    dao.phoneNum =t.phone;
    dao.sortKey =@"";
    
    dao.photoId =0;
    dao.lookUpKey =@"";
    dao.selected =0;
    dao.formattedNumber =@"";
    
    dao.pinyin =@"";
    dao.version =@"";
    dao.note =@"";
    dao.group_id =0;
    dao.group_name =t.group;
    
    NSArray *keyArr =@[@"id",@"contactId",@"displayName",@"phoneNum",@"sortKey",@"photoId",
                       @"lookUpKey",@"selected",
                       @"formattedNumber",@"pinyin",@"version",@"note",@"group_id",@"group_name"];
    NSMutableDictionary *dic =[dao mj_keyValuesWithKeys:keyArr];
    return dic;
}
@end
